package com.shxzz.easy12306.framework.starter.web;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.shxzz.easy12306.framework.starter.convention.errorcode.BaseErrorCode;
import com.shxzz.easy12306.framework.starter.convention.exceptions.AbstractException;
import com.shxzz.easy12306.framework.starter.convention.result.Result;
import com.shxzz.easy12306.framework.starter.convention.result.Results;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Optional;


/**
 * 全局异常处理器
 *
 * @author shxzz
 * @create 2024-01-27-20:53
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final String DEFAULT_ERROR_LOG_TEMPLATE = "[{}] {} [ex] {}";

    /**
     * 拦截请求参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> methodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest servletRequest) {
        FieldError fieldError = CollUtil.getFirst(ex.getFieldErrors());
        String errorMessage = Optional.ofNullable(fieldError).map(FieldError::getDefaultMessage).orElse(CharSequenceUtil.EMPTY);

        log.error(DEFAULT_ERROR_LOG_TEMPLATE, servletRequest.getMethod(), getFullURL(servletRequest), errorMessage);

        return Results.failure(BaseErrorCode.CLIENT_ERROR.code(), "请求参数校验错误：" + errorMessage);
    }

    /**
     * 拦截业务抽象异常
     */
    @ExceptionHandler(AbstractException.class)
    public Result<Void> abstractExceptionHandler(AbstractException ex, HttpServletRequest servletRequest) {
        if (ex.getCause() == null) {
            log.error(DEFAULT_ERROR_LOG_TEMPLATE, servletRequest.getMethod(), servletRequest.getRequestURL().toString(), ex.toString());
        } else {
            log.error(DEFAULT_ERROR_LOG_TEMPLATE, servletRequest.getMethod(), servletRequest.getRequestURL().toString(), ex, ex.getCause());
        }
        return Results.failure(ex);
    }

    /**
     * 拦截未捕获异常
     */
    @ExceptionHandler(Throwable.class)
    public Result<Void> defaultExceptionHandler(Throwable throwable, HttpServletRequest servletRequest) {
        log.error("[{}] {}", servletRequest.getMethod(), servletRequest.getRequestURL().toString(), throwable);
        return Results.failure();
    }

    /**
     * 获取完整的 URL，包括 query 参数
     */
    private String getFullURL(HttpServletRequest servletRequest) {
        if (StringUtils.hasLength(servletRequest.getQueryString())) {
            return servletRequest.getRequestURL() + "?" + servletRequest.getQueryString();
        }
        return servletRequest.getRequestURL().toString();
    }
}
